package com.ldc.framework.activity

import android.content.Context
import android.content.Intent
import android.os.Message
import android.view.View
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.ldc.commonlibs.conf.AppConf
import com.ldc.commonlibs.conf.RouteConf
import com.ldc.commonlibs.listener.OnRowListener
import com.ldc.commonlibs.uts.ApiUtils
import com.ldc.commonlibs.uts.MessageUts
import com.ldc.commonlibs.uts.ViewModelUtils
import com.ldc.commonres.common.VBMActivity
import com.ldc.commonres.views.StateViewLayout
import com.ldc.framework.R
import com.ldc.framework.adapter.CollectArticleAdapter
import com.ldc.framework.databinding.FrameworkActivityCollectArticleListBinding
import com.ldc.framework.model.ColletModel
import com.ldc.framework.viewmodel.FrameworkViewModelBase
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

class CollectArticleListActivity :
    VBMActivity<FrameworkActivityCollectArticleListBinding, FrameworkViewModelBase>() {
    private var page: Int = 0
    private var articleAdapter: CollectArticleAdapter? = null

    companion object {
        private const val ARG_TITLE = "title"
        private const val REFRESH_CODE = 0x12313

        fun start(context: Context, title: String) {
            context.startActivity(Intent(context, CollectArticleListActivity::class.java).apply {
                putExtra(ARG_TITLE, title)
            })
        }

        fun start(fragment: Fragment, title: String) {
            start(fragment.requireContext(), title)
        }
    }

    override fun processMessage(msg: Message): Boolean {
        when (msg.what) {
            REFRESH_CODE -> {
                getData()
            }
        }
        return super.processMessage(msg)
    }

    override fun initStateViewLayout(): StateViewLayout? =
        StateViewLayout.Companion.init(this, R.id.content_view)

    override fun main() {
        addOnReTryListener(object : OnRowListener<Int> {
            override fun onRow(v: View, data: Int) {
                page = 0
                MessageUts.sendMessage(getHandler(), REFRESH_CODE)
            }
        })
        addOnReTryListener(object : OnRowListener<Int> {
            override fun onRow(v: View, data: Int) {
                page = 0
                MessageUts.sendMessage(getHandler(), REFRESH_CODE)
            }
        })
        initAdapter()
        viewBind?.topBar?.let { top ->
            top.flBack.setOnClickListener { finish() }
            top.tvName.text = intent.run { getStringExtra(ARG_TITLE) }
        }
        viewBind?.contentView?.let { cv ->
            cv.refreshView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
                override fun onRefresh(refreshLayout: RefreshLayout) {
                    page = 0
                    MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                }

                override fun onLoadMore(refreshLayout: RefreshLayout) {
                    page += 1
                    MessageUts.sendMessage(getHandler(), REFRESH_CODE)

                }
            })
            MessageUts.sendMessage(getHandler(), REFRESH_CODE)
        }
    }

    override fun createViewBinding(): FrameworkActivityCollectArticleListBinding =
        FrameworkActivityCollectArticleListBinding.inflate(layoutInflater)

    override fun createViewModel(): FrameworkViewModelBase =
        ViewModelUtils.create(this, FrameworkViewModelBase::class.java)

    // 初始化适配器
    private fun initAdapter() {
        articleAdapter = CollectArticleAdapter().also { adapter ->
            adapter.addCollectRowListener(object : OnRowListener<ColletModel> {
                override fun onRow(v: View, data: ColletModel) {
                    viewModel?.uncollect("${data.id}", "${data.originId}")
                        ?.observe(this@CollectArticleListActivity) {
                            // 收藏
                            if (ApiUtils.isSuccess(it)) {
                                page = 0
                                MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                            }
                        }
                }
            })
            adapter.addOnRowListener(object : OnRowListener<ColletModel> {
                override fun onRow(v: View, data: ColletModel) {
                    ARouter.getInstance().build(RouteConf.WebViewRoute.startEnter)
                        .withString(AppConf.ARG_TITLE, data.title)
                        .withString(AppConf.ARG_URL, data.link)
                        .navigation()
                }
            })
        }
        viewBind?.contentView?.rv?.also { rv ->
            rv.recyclerview.adapter = articleAdapter
            rv.recyclerview.layoutManager =
                LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
            rv.recyclerview.setHasFixedSize(true)
        }


    }

    private fun getData() {
        showLoadingView()
        viewModel?.collectList(page)?.observe(this) {
            showContentView()
            viewBind?.contentView?.refreshView?.also { rf ->
                if (rf.state.isOpening) {
                    rf.finishRefresh()
                    rf.finishLoadMore()
                }
                rf.setNoMoreData(page == it.data?.pageCount)
            }
            if (ApiUtils.isSuccess(it)) {
                if (page == 0) {
                    articleAdapter?.newData(it.data?.datas)
                } else {
                    articleAdapter?.addNewData(it.data?.datas)
                }
            }
            if (articleAdapter?.isEmptyData()!!) {
                showEmptyView()
            }
        }
    }

}